package service

import (
	"context"
	"golang.org/x/sync/errgroup"
	"webook/interactive/domain"
	"webook/interactive/repository"
)

//go:generate mockgen -source=./interactive.go -package=svcmocks -destination=./mocks/interactive.mock.go InteractiveService
type InteractiveService interface {
	//biz代表业务 bizId代表业务资源id
	IncrReadCnt(ctx context.Context, biz string, bizId int64) error
	Like(ctx context.Context, biz string, bizId int64, uid int64) error
	CancelLike(ctx context.Context, biz string, bizId int64, uid int64) error
	Collect(ctx context.Context, biz string, bizId, cid, uid int64) error
	Get(ctx context.Context, biz string, bizId int64, uid int64) (domain.Interactive, error)
	GetByIds(ctx context.Context, biz string, ids []int64) (map[int64]domain.Interactive, error)
	QueryTopK(ctx context.Context, biz string, rankCnt int64) ([]int, error)
}

type interactiveService struct {
	repo repository.InteractiveRepository
}

func (i *interactiveService) QueryTopK(ctx context.Context, biz string, rankCnt int64) ([]int, error) {
	return i.repo.QueryTopK(ctx, biz, rankCnt)
}
func (i *interactiveService) GetByIds(ctx context.Context,
	biz string, ids []int64) (map[int64]domain.Interactive, error) {
	intrs, err := i.repo.GetByIds(ctx, biz, ids)
	if err != nil {
		return nil, err
	}
	res := make(map[int64]domain.Interactive, len(intrs))
	for _, intr := range intrs {
		res[intr.BizId] = intr
	}
	return res, nil
}

func (i *interactiveService) Get(ctx context.Context, biz string, bizId int64, uid int64) (domain.Interactive, error) {
	intr, err := i.repo.Get(ctx, biz, bizId) //阅读 点赞 收藏总数
	if err != nil {
		return domain.Interactive{}, err
	}
	var eg errgroup.Group
	eg.Go(func() error {
		intr.Liked, err = i.repo.Liked(ctx, biz, bizId, uid) //是否点赞
		return err
	})
	eg.Go(func() error {
		intr.Collected, err = i.repo.Collected(ctx, biz, bizId, uid) //是否收藏
		return err
	})
	err = eg.Wait()
	//打印日志
	return intr, err
}

func (i *interactiveService) Collect(ctx context.Context, biz string, bizId, cid, uid int64) error {
	return i.repo.AddCollectionItem(ctx, biz, bizId, cid, uid)
}

func (i *interactiveService) IncrReadCnt(ctx context.Context, biz string, bizId int64) error {
	return i.repo.IncrReadCnt(ctx, biz, bizId)
}
func (i *interactiveService) Like(ctx context.Context, biz string, bizId int64, uid int64) error {
	//IncrLikeCnt(ctx, biz,bizId, uid,1)
	return i.repo.IncrLikeCnt(ctx, biz, bizId, uid)
}

func (i *interactiveService) CancelLike(ctx context.Context, biz string, bizId int64, uid int64) error {
	//IncrLikeCnt(ctx, biz,bizId, uid,-1)
	return i.repo.DecrLikeCnt(ctx, biz, bizId, uid)
}
func NewInteractiveService(repo repository.InteractiveRepository) InteractiveService {
	return &interactiveService{
		repo: repo,
	}
}
